A = imread('cameraman.tif');
B = imnoise(A,'salt & pepper',0.04);
[row,col] = size(A);
figure, imshow(A);
figure, imshow(B);
C = padarray(A,[1,1]);
for  x = 2: (row-1)
   for y = 2 : (row-1) 
      a1 = [C(x-1,y-1) C(x-1,y) C(x-1,y+1) C(x,y-1) C(x,y) C(x,y+1) C(x+1,y-1) C(x+1,y) C(x+1,y+1)];
      a2 = sort(a1);
      med = a2(5);
      C(x,y) = med;
end
end
figure,imshow(C);